﻿using System.IO;
using System.Web.UI;
using GBlog.Core.Recaptcha;

namespace System.Web.Mvc
{
    public static class HtmlExtensions
    {
        public static IHtmlString Raw(this HtmlHelper helper, string html)
        {
            return MvcHtmlString.Create(html);
        }

        public static IHtmlString GenerateCaptcha(this HtmlHelper helper)
        {
            return helper.GenerateCaptcha("recaptcha", "default");
        }

        public static IHtmlString GenerateCaptcha(this HtmlHelper helper, string id, string theme)
        {
            if (string.IsNullOrEmpty(RecaptchaControlMvc.PublicKey) || string.IsNullOrEmpty(RecaptchaControlMvc.PrivateKey))
            {
                throw new ApplicationException("reCAPTCHA needs to be configured with a public & private key.");
            }
            RecaptchaControl recaptchaControl = new RecaptchaControl
            {
                ID = id,
                Theme = theme,
                PublicKey = RecaptchaControlMvc.PublicKey,
                PrivateKey = RecaptchaControlMvc.PrivateKey
            };
            HtmlTextWriter htmlTextWriter = new HtmlTextWriter(new StringWriter());
            recaptchaControl.RenderControl(htmlTextWriter);
            return helper.Raw(htmlTextWriter.InnerWriter.ToString());
        }
    }
}